package com.gable.report.controller;

import com.alibaba.fastjson.JSON;
import com.gable.report.common.util.HttpHelper;
import com.gable.report.common.util.ReturnResultUtil;
import com.gable.report.model.User;
import com.gable.report.util.FileUploadUtil;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.gable.report.util.HttpProcessUtil.getAccessPath;
import static com.gable.report.util.HttpProcessUtil.headerList;

/**
 * Created by gable on 2018/8/29.
 */
@Controller
@RequestMapping("/parameter")
public class ChartsParameterOperationController {

    private final Log logger = LogFactory.getLog(this.getClass());

    private static final String rootPath = "/charts/parameter/operation/";

    @Autowired
    HttpServletRequest request;

    @Value("${hospital.address}")
    String hospitalAddress;

    /**
     * @Author: 杨青桦
     * @Description:  查询设备报修处理时需要的合同信息
     * @Date: 2018/3/23 17:22
     */
    @RequestMapping(value="/contract/getContractInfo",method= RequestMethod.POST,produces="application/json;charset=utf-8")
    @ResponseBody
    public ReturnResultUtil getContractInfo(String assetsId) {
        String result;
        try {
            Map<String, String> paramMap = new HashMap<>();
            paramMap.put("assetsId",assetsId);    //设备id
            String path = rootPath + "contract/getContractInfo";    //接口路径
            String url = getAccessPath(hospitalAddress,path); //访问完整路径
            result = HttpHelper.postRequestResponseBodyAsString(headerList,url, paramMap);
            if(StringUtils.isEmpty(result)){
                return new ReturnResultUtil(0, "网络异常",result);
            }
            return JSON.parseObject(result,ReturnResultUtil.class);
        } catch (Exception e){
            e.printStackTrace();
            return new ReturnResultUtil(0,"查询异常");
        }
    }


    /**
     * @Author: 杨青桦
     * @Description: 报修指派处理(有合同的情况下)
     * @Date: 2018/3/26 14:54
     * @param request
     * @param id
     * @param serviceProviderId
     * @param repairType
     * @param maintenanceType
     * @return
     */
    @RequestMapping(value="repair/addDispatchInfo",method=RequestMethod.POST,produces="application/json;charset=utf-8")
    public @ResponseBody String addDispatchInfo(HttpServletRequest request,
                                                String id,
                                                String serviceProviderId,
                                                String repairType,
                                                String maintenanceType) {
        User user = (User) request.getSession().getAttribute("loginUser");
        String result;
        try {
            Map<String, String> paramMap = new HashMap<>();
            paramMap.put("user",JSON.toJSONString(user));
            paramMap.put("rid", id);									// 维修id
            paramMap.put("serviceProviderId", serviceProviderId);		// 维修商ID
            paramMap.put("repairType", repairType); 					// 维修类型(5001:自己修、5002:维修商修、5003:其他维修)
            paramMap.put("maintenanceType",maintenanceType);			// 维修方式（无<0>、送修<1>）
            String path = rootPath + "repair/addDispatchInfo";          //接口路径
            String url = getAccessPath(hospitalAddress, path);          //访问完整路径
            result = HttpHelper.postRequestResponseBodyAsString(headerList, url, paramMap);
            if(StringUtils.isEmpty(result)){
                return JSON.toJSONString(new ReturnResultUtil(0, "网络异常",result));
            }
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            return JSON.toJSONString(new ReturnResultUtil(0, "操作异常"));
        }
    }


    /**
     * @Author: 杨青桦
     * @Description:  报修(紧急,择期)item查询
     * @Date: 2018/8/29 13:13
     * @param request
     * @param type
     * @return
     */
    @RequestMapping(value = "base/queryItem", method = RequestMethod.POST,produces="application/json;charset=utf-8")
    @ResponseBody
    public ReturnResultUtil queryItem(HttpServletRequest request, String type) {
        User user = (User) request.getSession().getAttribute("loginUser");
        String result;
        try {
            Map<String, String> paramMap = new HashMap<>();
            paramMap.put("user",JSON.toJSONString(user));
            paramMap.put("type", type);									//
            String path = rootPath + "base/queryItem";          //接口路径
            String url = getAccessPath(hospitalAddress, path);          //访问完整路径
            result = HttpHelper.postRequestResponseBodyAsString(headerList, url, paramMap);
            if(StringUtils.isEmpty(result)){
                return new ReturnResultUtil(0, "网络异常",result);
            }
            return JSON.parseObject(result,ReturnResultUtil.class);
        } catch (Exception e) {
            e.printStackTrace();
            return new ReturnResultUtil(0,"查询异常");
        }
    }


    /**
     * @Author: 杨青桦
     * @Description: 报修接口
     * @Date: 2018/3/26 14:54
     * @param request
     * @param deviceId
     * @param contractInfoId
     * @param faultTime
     * @param emergencyDegree
     * @param assetsStatus
     * @param fault
     * @return
     */
    @RequestMapping(value="repair/addRepair",method=RequestMethod.POST,produces="application/json;charset=utf-8")
    public @ResponseBody String addRepair(HttpServletRequest request,
                                                String deviceId,
                                                String contractInfoId,
                                                String faultTime,
                                                String emergencyDegree,
                                                String assetsStatus,
                                                String parameterEventResultId,
                                                String fault) {
        User user = (User) request.getSession().getAttribute("loginUser");
        Map<String,Object> resultMap = new HashMap<>();
        // 上传图片模块
        String key = "";
        String photos = "";
        try {
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");	// 设置日期格式
            StringBuffer sb = new StringBuffer();								// 推送信息
            MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
            List<MultipartFile> files = multipartRequest.getFiles("files");
            if(files != null && files.size()>0){
                for(MultipartFile m : files){
                    if(m.getBytes().length != 0) {
                        String suffix = m.getOriginalFilename()
                                .substring(m.getOriginalFilename().lastIndexOf(".") + 1);
                        Long fileName = new Date().getTime();
                        key = "repair/" + fileName + "." + suffix;
                        boolean bl = FileUploadUtil.fileUpload(m.getBytes(), key, m.getSize());

                        if (!bl) {
                            resultMap.put("msg", "上传文件失败");
                            return JSON.toJSONString(resultMap);
                        }
                        //红房子医院放开
//				new Thread(new FileUploadThread(m.getBytes(),key)).start();
                        if (FileUploadUtil.IsLocalUpload.equals("true")) {
                            photos += FileUploadUtil.AccessAddress + FileUploadUtil.ROOTURL + "repair/" + fileName + "." + suffix + ",";
                        } else {
                            photos += FileUploadUtil.REALMNAME + "/" + key + ",";
                        }
                    }
                }
            }else{
                resultMap.put("ret",1);
                resultMap.put("msg","无文件上传");
            }
        } catch (IOException e) {
            e.printStackTrace();
            resultMap.put("ret",0);
            resultMap.put("msg","文件上传失败");
        }
        //文件上传失败,直接返回失败信息
        if(resultMap.get("ret") != null &&(Integer)resultMap.get("ret") == 0){
            return JSON.toJSONString(resultMap);
        }
        try{
            String result;
            Map<String, String> paramMap = new HashMap<>();
            paramMap.put("user",JSON.toJSONString(user));
            paramMap.put("photos", photos);								// 故障图片
            paramMap.put("deviceId", deviceId);		                    // 设备ID
            paramMap.put("faultTime", faultTime);		                // 故障时间
            paramMap.put("contractInfoId", contractInfoId); 			//
            paramMap.put("emergencyDegree",emergencyDegree);			//
            paramMap.put("assetsStatus", assetsStatus); 			    //
            paramMap.put("parameterEventResultId", parameterEventResultId); 			    //
            paramMap.put("fault",fault);			                    //
            String path = rootPath + "repair/addRepair";                //接口路径
            String url = getAccessPath(hospitalAddress, path);          //访问完整路径
            result = HttpHelper.postRequestResponseBodyAsString(headerList, url, paramMap);
            if(StringUtils.isEmpty(result)){
                return JSON.toJSONString(new ReturnResultUtil(0, "网络异常",result));
            }
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            return JSON.toJSONString(new ReturnResultUtil(0, "操作异常"));
        }
    }



}
